package x.ovo.wechat.bot.impl.http.request.contact;

import lombok.RequiredArgsConstructor;
import org.dromara.hutool.core.net.url.UrlBuilder;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import x.ovo.wechat.bot.core.Constant;
import x.ovo.wechat.bot.core.entity.BatchContactQuery;
import x.ovo.wechat.bot.core.entity.Contact;
import x.ovo.wechat.bot.core.http.request.ApiRequest;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;

@RequiredArgsConstructor
public class BatchContactRequest extends ApiRequest<List<Contact>> {

    private final Collection<BatchContactQuery> queries;

    @Override
    public ApiRequest<List<Contact>> build() {
        String s = UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.Urls.BATCH_GET_CONTACT)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("pass_ticket", this.session.getPassTicket())
                .addQuery("type", "ex")
                .build();
        return this.setUrl(s)
                .setMethod(POST)
                .setJson(true)
                .addParameter("BaseRequest", this.baseRequest)
                .addParameter("Count", this.queries.size())
                .addParameter("List", this.queries);
    }

    @Override
    protected Function<String, List<Contact>> stringHandler() {
        return s -> {
            JSONObject json = JSONUtil.parseObj(s);
            if (json.<Integer>getByPath("BaseResponse.Ret", Integer.class) == 0) {
                return json.getBeanList("ContactList", Contact.class);
            }
            return List.of();
        };
    }
}
